﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace NCRGEA.UserControls
{
    public partial class ucPrograms_Edit : UserControl
    {
        private int _MemberID;
        public int MemberID
        {
            get
            {
                return _MemberID;
            }
            set
            {
                _MemberID = value;
            }
        }

        private int _PlanID;
        public int PlanID
        {
            get
            {
                return _PlanID;
            }
            set
            {
                _PlanID = value;
                PopulateControls();
            }
        }

        DataTable dtParticipants;

        public ucPrograms_Edit()
        {

            InitializeComponent();
            dtParticipants = new DataTable();
            dtParticipants.Columns.Add("FirstName");
            dtParticipants.Columns.Add("LastName");
            dtParticipants.Columns.Add("StartDate",DateTime.Now.GetType());
            dtParticipants.Columns.Add("Relation", (new int().GetType()));
            dtParticipants.Columns.Add("RelationShow");
        }

        private void PopulatePrograms()
        {
            string sqlQry = @"SELECT
	                                ProgramID,
	                                Description,
	                                Amount
                                FROM
	                                memPrograms
                                WHERE
	                                ProgramTypeID=(SELECT
						                                pr.ProgramTypeID
					                                FROM
						                                memPlans pl
						                                INNER JOIN
							                                memPrograms pr
						                                ON
							                                pl.ProgramID=pr.ProgramID
					                                WHERE
						                                pl.PlanID=@PlanID)";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@PlanID", _PlanID) { SqlDbType = SqlDbType.Int };
            DataTable result = AAL.DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count == 0)
                return;
            cmbPrograms.DataSource = result;
            cmbPrograms.DisplayMember = "Description";
        }

        private void PopulateRelations()
        {
            //string qry = @"SELECT Relation, Description FROM memRelations";
            //DataTable results = AAL.DAL.ExecuteQuery(qry);
            //if (results != null)
            //{
            //    if (results.Rows.Count == 0)
            //    {
            //        //Something bad happened.
            //        ShowProgramsList();
            //        return;
            //    }

            //    cmbRelation.DataSource = results;
            //    cmbRelation.DisplayMember = "Description";
            //    cmbRelation.SelectedIndex = 0;
            //}
        }

        private void PopulateParticipants()
        {
            string sqlQry = @"SELECT
	                            mp.ParticipantID,
	                            mp.FirstName,
	                            mp.LastName,
	                            mp.Relation,
	                            mr.Description,
	                            mp.StartDate,
	                            mp.Active
                            FROM
	                            memParticipants mp
	                            INNER JOIN
		                            memRelations mr
	                            ON
		                            mp.Relation=mr.Relation
                            WHERE
	                            mp.PlanID=@PlanID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@PlanID", _PlanID) { SqlDbType = SqlDbType.Int };
            DataTable result = AAL.DAL.ExecuteQuery(sqlQry, sParamArray);
            grdParticipants.DataSource = result;
        }


        private void PopulateControls()
        {
            grdParticipants.DataSource = dtParticipants;
            PopulatePrograms();
            PopulateRelations();
            PopulateParticipants();

            string sqlQry = @"SELECT
	                                pl.PlanID,
	                                pl.ProgramID,
	                                pl.MemberID,
	                                pl.StartDate,
	                                pl.Active,
	                                pr.Description
                                FROM
	                                memPlans pl
	                                INNER JOIN
		                                memPrograms pr
	                                ON
		                                pl.ProgramID=pr.ProgramID
                                WHERE
	                                pl.PlanID=@PlanID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@PlanID", _PlanID) { SqlDbType = SqlDbType.Int };
            DataTable result = AAL.DAL.ExecuteQuery(sqlQry, sParamArray);
            cmbPrograms.Text = result.Rows[0]["Description"].ToString();
            dateStartDate.Value = (DateTime)result.Rows[0]["StartDate"];
            grdParticipants.Columns["Active"].ReadOnly = true;
            grdParticipants.Columns["Description"].ReadOnly = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ShowProgramsList();
        }

        private void ShowProgramsList()
        {
            //Flip back to the list of programs
            this.Parent.Controls.Add(new ucPrograms() { MemberID = _MemberID, Dock = DockStyle.Fill });
            this.Parent.Controls.Remove(this);
        }

        private void cmbPrograms_Leave(object sender, EventArgs e)
        {
            if (cmbPrograms.SelectedIndex == -1)
                cmbPrograms.SelectedIndex = 0;
        }

        private void cmbPrograms_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblAmount.Text = ((DataRowView)cmbPrograms.SelectedValue)["Amount"].ToString();
        }

        private void grdParticipants_KeyUp(object sender, KeyEventArgs e)
        {
            if (grdParticipants.SelectedRows.Count <= 0)
                return;
            if (e.KeyCode == Keys.Delete)
            {
                DialogResult dr = MessageBox.Show("Are you sure that you want to delete the selected particpant(s)?", "NCRGEA", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No)
                    return;
                else
                    foreach (DataGridViewRow dgvr in grdParticipants.SelectedRows)
                        dtParticipants.Rows.Remove(((DataRowView)dgvr.DataBoundItem).Row);
                grdParticipants.DataSource = dtParticipants;
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string qry = @"SELECT
	                            mp.ParticipantID,
	                            mp.FirstName,
	                            mp.LastName,
	                            mp.Relation,
	                            mp.StartDate,
	                            mp.Active
                            FROM
	                            memParticipants mp
                            WHERE
	                            mp.PlanID=" + _PlanID;
            try
            {
                SqlDataAdapter sAdapter = new SqlDataAdapter(qry, AAL.DAL.GetSqlConnection());
                SqlCommandBuilder sCB = new SqlCommandBuilder(sAdapter);
                sAdapter.UpdateCommand = sCB.GetUpdateCommand();
                sAdapter.Update((DataTable)grdParticipants.DataSource);
            }
            catch (Exception eX)
            {
                Logger.Log("Failed to update participants: " + eX.Message);
                MessageBox.Show("Failed to save data!");
                return;
            }
            ShowProgramsList();

            int ProgramID = (int)((DataRowView)cmbPrograms.SelectedValue)["ProgramID"];
            DateTime StartDate = dateStartDate.Value;

            //if (!AAL.UAL.RegisterProgram(ProgramID, _MemberID, StartDate, dtParticipants))
            //{
            //    MessageBox.Show("An error occurred while registering for this program!");
            //}
            //else
            //{
            //    ShowProgramsList();
            //}
        }

        private void grdParticipants_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

            MessageBox.Show("Invalid data in column " + ((DataTable)grdParticipants.DataSource).Columns[e.ColumnIndex].ToString() + "!");
            
        }
    }
}
